package niu.fencer.tool.qrcode.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.king.zxing.util.CodeUtils;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import niu.fencer.tool.qrcode.R;
import niu.fencer.tool.qrcode.util.Encoder;
import niu.fencer.tool.qrcode.util.FileUtil;
import niu.fencer.tool.qrcode.util.LogUtil;
import niu.fencer.tool.qrcode.util.StringUtil;

public class QrCodeGenActivity extends AppCompatActivity   {

    BottomNavigationView _bottomNav;
    ImageView imgQrCode;
    ImageView back;
    TextView share;
    Handler qrCodeHandler=null;
    Encoder encoder=null;
    TextView title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr_code_gen);



        imgQrCode=findViewById(R.id.imgQrCode);
        back=findViewById(R.id.back);
        share=findViewById(R.id.share);
        title=findViewById(R.id.title);

//        ViewPager2 viewPager = (ViewPager2) findViewById(R.id.viewPager2);
//        LogUtil.i("viewPager:"+viewPager);
//        viewPager.setAdapter(new QrCodeGenStyleAdapter(this, viewPager));

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QrCodeGenActivity.this.finish();
            }
        });

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupMenu(v);
            }
        });

        qrCodeHandler=new Handler(Looper.getMainLooper()) {
            public void handleMessage(Message msg) {
                byte[] part=msg.getData().getByteArray("qrdata");
                int index=msg.getData().getInt("index");

                String base64Str= Base64.encodeToString(part,Base64.DEFAULT);
                crateQRCode(base64Str);
                if(encoder!=null)
                    title.setText(encoder.total+"|"+index);
            }
        };

        Intent intent=getIntent();
        if(intent!=null){
            Boolean isFile=intent.getBooleanExtra(MainActivity.IS_FILE,false);
            String source=intent.getStringExtra(MainActivity.QRCODE_SOURCE);
            String fileName="NO_NAME";
            LogUtil.i("source:"+source);
            byte[] data =null;
            if(isFile){
                if(!StringUtil.isEmpty(source)) {
                    File f = new File(source);
                    data = FileUtil.readFileFast(f);
                    fileName = f.getName();
                }
            }else{
                data=source.trim().getBytes();
            }
            int splitSize=120;
            if(data!=null&&data.length>0) {
                if(data.length>splitSize){
                    encoder = new Encoder();
                    byte[][] rangeArray = encoder.encode(data, splitSize,fileName);// sizeSplit
                    MyThread curTask=new MyThread(rangeArray);
                    curTask.start();
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            crateQRCode(source);
                        }
                    });
                }
            }
        }
    }
    private void crateQRCode(String str){
        //配置参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put( EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);///容错级别
        hints.put(EncodeHintType.MARGIN, 3); ////设置空白边距的宽度

        Bitmap bitmap = CodeUtils.createQRCode(str,800,null,0,hints);
        imgQrCode.setImageBitmap(bitmap);
    }
    private void showPopupMenu(View view){
        PopupMenu popupMenu = new PopupMenu(this,view);
        popupMenu.inflate(R.menu.menu_share);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.action_1:
                        Toast.makeText(getBaseContext(),"Option 1",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.action_2:
                        Toast.makeText(getBaseContext(),"Option 2",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.action_3:
                        Toast.makeText(getBaseContext(),"Option 3",Toast.LENGTH_SHORT).show();
                        return true;
                    default:
                        //do nothing
                }

                return false;
            }
        });
        popupMenu.show();
    }

    class MyThread extends Thread{
        int i=0;
        volatile  boolean isRun=true;
        byte[][] rangeArray;
        public MyThread(byte[][] rangeArray){
            this.rangeArray=rangeArray;
        }
        @Override
        public void run() {
            while(isRun){
                Message msg= Message.obtain();

                Bundle data=new Bundle();
                data.putByteArray("qrdata",rangeArray[i]);
                data.putInt("index",i);

                msg.setData(data);
                qrCodeHandler.sendMessage(msg);
                i++;
                if(i>=rangeArray.length){
                    i=0;
                }
                try {
                    Thread.sleep(50);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }}
}